var loadedVar = false
var paused = false
var timeId = -1; // if an segment of the sound track is played, this variable is used
var mediaPlayerLoadedCheckTimerId = window.setInterval(check, 500); // checks for when media player is ready to be played
var documentReadyToPlay = false; // set to true when document dom ready
document.addEventListener("DOMContentLoaded", loaded, false);

function set(){
	//document.getElementById("visibility").checked  = false
	//document.getElementById("toggle").disabled = true;
}	

function check(){
	player =  document.getElementById("player"); //document.getElementsByTagName("audio")[0];
	if (player != null){
		//document.addEventListener("DOMContentLoaded", loaded, false);
		if (player.readyState > 3){
			try{
				launch();
				clearInterval(mediaPlayerLoadedCheckTimerId)
				//if (documentReadyToPlay){
					//player.play();
					//alert("ready l");
				//}			
			}
			catch(er){
				console.log("unable to init media player" + er);
			}
		}
	}
}

function getTime(){
	return player.currentTime;
}
function stop(){
	//console.log("stop");
	player.pause();
	return getTime();
}

function setTime(value){
	player.currentTime = value;	
}

function playAt(value){
	//console.log("playAt");
	player.currentTime = value;
	player.play();
}
function play(){
	player.play();
}

function playSegment(from, to){
	player.currentTime = from;
	player.play();
	stopTime = (to - from);
	timeID = setTimeout(pause, stopTime * 1000);
}


/*
Called when the document dom is ready, begin playing the audio and enable the pause button
*/
var content;
var centerImage;
function launch(){
	documentReadyToPlay = true;
	content = document.getElementById("content");
	//document.cre
	centerImage = document.getElementById("image");
	//centerImage = document.createElement("div");
	//centerImage.setAttribute("id","image");
	//centerImage.className = "";
	//centerImage.setAttribute("id", "image");
	//document.body.appendChild(centerImage);
	
	//play();
	var toggleButton = document.getElementById("toggle");
	toggleButton.disabled=false;
	toggleButton.focus();	
}


window.onkeydown = keypress;
function keypress(evt){
	keyListener(evt);
}


function clearTimer() {
  if (timeId != -1) {
    window.clearInterval(timeId);
    timeId = -1;
  }
}
var displayedImageStyle;
function changeModeToPlay() {
	elem = document.getElementById("toggle");
	elem.value="Pause ||";
	paused = false;
	if (hideText){
		activateHideText();

	}
}

var currentImageIndex;
function checkForImageUpdate(){
	var index = getImageIndex(getTime());
	if (index != currentImageIndex){
		setImage(index);
	}
}

function setImage(index){
	currentImageIndex = index;
	var image = document.getElementById("image" + index);
	centerImage.innerHTML = image.outerHTML;
	var width = parseInt(image.clientWidth);
	var height = parseInt(image.clientHeight);
	var widthRadius = parseInt(width/2);
	var heightRadius = parseInt(height/2);
	centerImage.style.marginLeft = -widthRadius + "px";
	centerImage.style.marginTop = -heightRadius + "px";
	centerImage.style.visibility = "visible"
}
var imageUpdateId = -1;
function activateHideText(){
	if (imageTimes !== undefined){
		var index = getImageIndex(getTime());
		if (index != null){
			setImage(index)
			//centerImage.style.display = "block";
		}
		imageUpdateId = window.setInterval(checkForImageUpdate, 1000);
	}
	//content.style.visibility = "hidden";
	content.style.opacity = "0";
	//image.style.opacity = "1"
}

function changeModeToPause() {
	elem = document.getElementById("toggle");
	elem.value="Play >";
	paused = true;
}

function pause() {
	var time = stop();
	changeModeToPause();
	readingPause(time);
}
function playset(){
	changeModeToPlay();
}
function hideTextChange(element){
	if (playing){
		if (element.checked){
			hideText = true;
			activateHideText();
		}
		else{
			clearInterval(imageUpdateId);
			centerImage.style.visibility = "collapsed";
			content.style.visibility = "visible";
			content.style.opacity = "1";
			hideText = false;
		}
	}
	else{
			if (element.checked){
				hideText = true;
			}
			else{
				hideText = false;
			}
	}
}


var hideText = false;
function tog() {
	elem = document.getElementById("toggle")
	if (paused){		 
		start();
		changeModeToPlay();
	}
	else {
		pause();
		if (hideText){
			//var image = document.getElementById("image1");

			//var centerImage = document.getElementById("image");
			centerImage.style.visibility = "collapse";
			content.style.visibility = "visible";
			content.style.opacity = "1";
		}
	}	
}

function getImageIndex(time){
	if (imageTimes !== undefined){
		var length = imageTimes.length;
		for (i = 0; i < length; i++){
			if (imageTimes[i] > time){
				return i + 1;
			}
		}
	}
	return null;
}


function changeOpacity(){
	content.style.opacity = "1";
}

/*if (document.all) { 
docObj = "document.all."
styleObj = ".style"
ie =true
var appVer = navigator.appVersion.toLowerCase();
var iePos  = appVer.indexOf('msie');
//version = parseFloatappVer.substring(iePos+5,appVer.indexOf(';',iePos)));
       //is_major = parseInt(is_minor);
	//alert(is_minor)
}
else
{
docObj = "document."  
styleObj = ""
ie =false
}*/
var ie;
if (document.getElementsByClassName){
	ie = false;
}
else{
	ie = document.all;
}
//var version;
//var readingid = 0;
var tip;
var ns6;
//var ie;
var showing = false;
var offsetfromcursorX=2;//10; //Customize x offset of tooltip
var offsetfromcursorY=2;//20; //Customize y offset of tooltip

function showTipIE(evt, tip) { 
	tip.style.visibility = "visible";
	showing = true;
	position(evt, tip, 10, 20);
}

function positiontip(evt){
	if (showing){
		position(evt, tip, 10, 20);
	}
}
function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}
function position(e, popup, offsetfromcursorX, offsetfromcursorY){
		//
		popup.style.top = offsetfromcursorY  + content.scrollTop + "px";
		popup.style.left = offsetfromcursorX;
		/*var nondefaultpos=false;
		var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
		var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
		//Find out how close the mouse is to the corner of the window
		var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20;
		var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20;
	
		var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX;
		var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY;
	
		var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000;
	
		//if the horizontal distance isn't enough to accomodate the width of the context menu
		if (rightedge<popup.offsetWidth){
		//move the horizontal position of the menu to the left by it's width
			popup.style.left=curX-popup.offsetWidth+"px";
			nondefaultpos=true;
		}
		else if (curX<leftedge)
		{popup.style.left="5px";}
		else{
		//position the horizontal position of the menu where the mouse is positioned
			popup.style.left=curX+offsetfromcursorX+"px";
		//pointerobj.style.left=curX+offsetfromcursorX+"px";
		}
	
		//same concept with the vertical position
		if (bottomedge<popup.offsetHeight){
			popup.style.top=curY-popup.offsetHeight-offsetfromcursorY+"px";
			nondefaultpos=true;
			//elem.parentNode.offsetTop + elem.parentNode.offsetHeight  + "px";
		}
		else{
			popup.style.top=curY+offsetfromcursorY+"px";
		}
		*/
}


function hide(){
	tip.style.display = "none";
	if (def != null)
		def.className = "linked";
}

var def;
function showtip(evt) { 
	var id = getId(evt);
	def = document.getElementById(id);
//	alert(def.className );
	def.className = "active";
	//	alert(def.className );
	tip = document.getElementById('d'+ id);
	showElement(tip, evt);
	showing = true;
}

function showElement(elem, evt){
	var x;
	var y;
	if (ie){
		x = evt.clientX;
		y = evt.clientY;
	}
	else{
		x = evt.pageX;
		y = (evt.pageY + content.scrollTop) - content.offsetTop;
	}
	elem.style.left = (x  + 5) + "px";
	elem.style.top = (y  + 12)+ "px";
	elem.style.display = "block";
	elem.style.position = "absolute";
}

function saveDefinition(event){
	var sentence;
	if (ie){
		//event.scrElement.innerHTML
		sentence = contextMenuTarget.parentNode.innerText;
	}
	else{
		sentence = contextMenuTarget.parentNode.innerHTML.replace(/<[^>]+>/g,"");
	} 
	translation = eval("a" + contextMenuTarget.id);
	readingid = 0;
	language = "none";	

	DefinitionSaver.saveDefintion(readingid, language, contextMenuTarget.parentNode.id, translation, contextMenuTarget.innerHTML, sentence, callBack);

}

function callBack(result)
{ 
	if (!result)
		alert("You must be logged in to save a definition!")
}


var selected = false

function deselectAll() { 
	if (selected){
		selected = false
		deselect(currentWord);
		//var arrowTop = document.getElementById("arrow_line");
		//arrowTop.style.visibility = "hidden";
		//deselect(previousWord);
		//deselect(nextWord);
	}
}
function deselect(elem) { 
	if (elem != null){
		/*elem.style.fontWeight= "normal";
		elem.style.borderBottom = "none";
		elem.style.fontSize = "100%";
		elem.style.textShadow  = "";*/
		
		elem.className = className;
	}
}

function start() {
	deselectAll();
	if (jumpOccurred){
		jumpOccurred = false;
		toPlay = times[wordIndex];
	}
	playing = true;
	//setVisibility()
	// ap = document.getElementById("player") 
	if (toPlay != -1){
		
		//console.log("playAt" + toPlay);
		playAt(toPlay)
	}
	else{
		setTime(getTime()   - .05);
		play();
	}
}

/*function selectPreviousWord(elem){
	elem.style.fontSize = "120%";
	highlightWord(elem);
	previousWord = elem;
}
function selectNextWord(elem){
	elem.style.fontSize = "120%";
	highlightWord(elem);
	nextWord = elem;
}*/
//var nextWord;
//var previousWord;
var currentWord;
var shadow = "rgba(64, 64, 64, 0.5) 1px 1px 2px";

function selectCurrent(elem){
	//elem.style.fontSize = "140%";
	currentWord = elem;
	highlightWord(elem);
}

function highlightWord(elem) { 
	/*elem.style.borderBottomStyle = "solid"
	elem.style.borderBottomColor = "black"
	elem.style.borderBottomWidth = "1px"
	elem.style.textShadow  = shadow;
	elem.style.fontWeight= "bold";*/
	elem.className = "selected";
	
	/*var content = document.getElementById("content");	
	var arrowTop = document.getElementById("arrow_line");
	arrowTop.style.visibility = "visible";
	var selectedPosY = -content.scrollTop;
	var selectedPosX = 0;	
	var theElement = elem;
	while(theElement != null){
	    selectedPosY += theElement.offsetTop;
		selectedPosX += theElement.offsetLeft;
	    theElement = theElement.offsetParent;
	  }
	  var diameter = parseInt(elem.offsetWidth / 2) - 4;
	arrowTop.style.top = (selectedPosY - 10)+ "px";
	arrowTop.style.left = (selectedPosX + diameter) + "px";
*/	

}

function getElementId(time) {	
	size = times.length;
	for (i = 0; i < size; i++) {
	    dbl = times[i];
	    if (dbl > time) {
		 	return className + i;
	    }
	}
	return "w0";
 }
 
 function getTimeIndex(time) {	
	size = times.length;
	for (i = 0; i < size; i++) {
	    dbl = times[i];
	    if (dbl > time) {
		 	return parseInt(i - 1);
	    }
	}
	return 0;
 }

function  scroll( theElement) {
	//theElement.scrollIntoView(false);
	
	  var selectedPosY = 0;
	              
	  while(theElement != null){
	    selectedPosY += theElement.offsetTop;
	    theElement = theElement.offsetParent;
	  }
	  selectedPosY = selectedPosY - content.offsetTop
	//  alert(window.screen.availHeight);
	var half = parseInt((window.screen.availHeight - content.offsetTop) / 3) - 10;
	//var modalPage =	document.getElementBsyId("content");
	content.scrollTop = selectedPosY - half;
	//modalPage.scrollTo(0,);
  }

var playing = true;
var toPlay = -1;

var wordIndex;
function jumpBack() {	
	if (playing){
		var time = getTime();
		time = time - 3;
		if (time < 0){
			time = 0;
		}
		playAt(time);	
	}
	else {
		//setTime(time);
		jumpOccurred = true;
		wordIndex = wordIndex - 1;
		if (wordIndex < 0)
			wordIndex = 0;
		//wordIndex = getTimeIndex(time);
		deselectAll();
		selectById(wordIndex);
	}
}
var jumpOccurred;
function jumpForward() {
	
	if (playing){
		var time = getTime();
		time = time + 3;
		if (time < 0){
			time = 0;
		}
		playAt(time);	
	}
	else {
		jumpOccurred = true;
		wordIndex = wordIndex + 1;
		//wordIndex = getTimeIndex(time);
		deselectAll();
		selectById(wordIndex);		
	}
}

/*
function setVisibility(){
	var mainPain = document.getElementById("main_pane");
	if (mainPain != null){
		var view = document.getElementById("slide");
		if (playing & hidden){
			mainPain.style.visibility = "hidden";
			mainPain.style.display = "none";
		 	view.style.display = "block";
		}
		else{
			 mainPain.style.display = "block";
		 	mainPain.style.visibility = "visible";	
		 	view.style.display = "none";
		}
	}
}


var hidden = false;

function toggleVisibility(){
	var modalPage =	document.getElementById("modalPage");
	if (hidden){
		modalPage.visibility ="visible";
	}
	else{
		//alert("hide");
		//modalPage.bgColor = "green";
		modalPage.visibility ="hidden";				
	}
}
/*function toggleVisibility(source){
	if (hidden){
		hidden = false;
		setVisibility();
		if (source == 'key')
			document.getElementById("visibility").checked  = false
		window.clearTimeout(slideTimeId)
	}
	else{
		checkSlide()
		slideTimeId = window.setInterval('checkSlide()', 1000);
		hidden = true;
		setVisibility();
		if (source == 'key')
			document.getElementById("visibility").checked  = true
	}
}
*/
function getWordId(evt){
	var id 
	if (!ie){
		id = evt.target.id;
	}
	else{
		id = evt.srcElement.id;
	}

	id = id.substring(1, id.length)
	return parseInt(id);
}

function getId(evt){
	var id;
	if (ie){
		id = evt.srcElement.id;
		if (id.substring(0, 1) == 'w'){
			return evt.srcElement.parentNode.id;
		}
		else{
			return id;
		}
	}
	else{
		id = evt.target.id;
		if (id.substring(0, 1) == 'w'){
			return evt.target.parentNode.id;
		}
		else{
			return id;
		}	
	}		
}
function move(evt){
	tip.style.left = evt.pageX + 5 + "px";
	tip.style.top = (evt.pageY  + content.scrollTop + 12) - content.offsetTop + "px";
	tip.style.position= "absolute";
}

function moveIE(evt){
	tip.style.left = evt.clientX + 5;
	tip.style.top = evt.clientY + 5;
	tip.style.position= "absolute";
}

var className;
function loaded(){
	if (document.getElementsByClassName) {
		var elems = document.getElementsByClassName("linked");
		for (i = 0 ; i < elems.length; i++){
			processLink(elems[i]);
		}
		elems = document.getElementsByClassName("translation");
		for (i = 0 ; i < elems.length; i++){
			processTranslation(elems[i]);
		}
		if (hasWordGranularity){
			className = "w";
		}
		else{
			className = "s";
		}
		elems = document.getElementsByClassName(className);

		for (i = 0 ; i < elems.length; i++){
			processWord(elems[i]);
		}
	 }
	else {
	  i = 0;
	  var elems = document.getElementsByTagName("span");
	  while (elem = elems[i++]) {
	    if (elem.className == "linked") {
    		  processLinkIE(elem);
		}
		else if (elem.className == "translation") {
			  processTranslationIE(elem, "translation");
		}
		else if (elem.className == "w"){
			processWordIE(elem);
		}
    }
  }


	//launch();
}

function playWord(evt){
	deselectAll();
	
	var id = getWordId(evt);
//	alert('play word');
	if (changedWord != null){
		changedWord.className = className;
	}
	changedWord=document.getElementById(className + id);
	changedWord.className += " clickedElement";
	setTimeout(removeWordClass, 200);
	//alert("play word" + document.getElementById("w" + (id)).className);
	playAtIndex(id + 1);
}
var changedWord;

function removeWordClass(){
	if (changedWord != null){
		changedWord.className = className;
		changedWord = null;
	}
}

function processWord(span){
	//console.log("word processed");
	span.onclick = playWord;		
}
function processWordIE(span){
	span.onclick = function(){ playWord(event)};		
}
function processTranslation(span){
	//span.onmouseover = showTranslationTip;
	span.addEventListener("touchstart", showTranslationTip);
	span.onmouseout = function(event){ hide()} ;
}

function processTranslationIE(span){
	span.onmouseover = function(){ showTranslationTip(event)};
	span.onmouseout = function(){ hide()} ;
}

function processLinkIE(span){
	span.onmouseover = function(){ showtip(event)};
	span.onmousemove = function(){ moveIE(event)};	
	span.onmouseout = function(){ hide()} ;
}

function processLink(span){
	//span.onmouseover = function(event){ showtip(event)};
	span.addEventListener("touchstart", showtip);
	span.onmousemove = function(event){ move(event)};	
	span.onmouseout = function(event){ hide()} ;
}
var oldId;
function showTranslationTip(evt) { 
	var id = getId(evt);
	oldId = id;
	if (tip && tip.style){
		console.log(tip.style.visibility);
		tip.style.visibility = "hidden";
	}
	//alert($(id).text());
	tip = document.getElementById('d'+ id);
	var elem = document.getElementById(id);
	tip.style.visibility = "visible";
	tip.style.position = "absolute";

	tip.style.display = "block";
	
		var width;
		if (document.width == null){
			width = document.body.clientWidth
		}
		else width = document.width;
		
		var maxWidth = width- elem.parentNode.offsetLeft;
	
	if (maxWidth > 300){
		if (!ie)
			tip.style.maxWidth = maxWidth;	
			//var modalPage =	document.getElementById("content");

		tip.style.left = elem.parentNode.offsetLeft +"px";
		tip.style.top 	= elem.parentNode.offsetTop + elem.parentNode.offsetHeight  + "px"; // - modalPage.scrollTop
	}
	else{
		if (!ie)
			tip.style.maxWidth = width - evt.pageX + 10;
		tip.style.left = evt.pageX + 10 +"px"; //elem.offsetLeft;
		tip.style.top = evt.pageY - content.offsetTop + content.scrollTop +"px";//elem.offsetTop;
	}

	//alert(tip.style.width);
	showing = true;
}


function playAtIndex(value) {
	//if (loaded ){
		//deselectAll()
		if (value == 0){
			playAt(0)
			if (!playing ){
				playset()
			}
		}
		else {	
			var toPlay = times[value -1];
			playAt(toPlay)
			if (!playing ){
				playset()
			}
		}
		playing = true
}
function goBack(jumpBack){
	if (playing)
		time = stop();
	else{ 
		playset();
		deselect();
		time = getTime();
	}
	paused = true;
	time = time - jumpBack
	if (time < 0)
		time = 0
	//alert(time);
	playAt(time)	
	paused = false;
}


function readingPause(time){
	//alert("pause");
	playing = false
	//setVisibility();
	// ap = document.getElementById("player") 

	//msg(time);
	toPlay = -1
	wordIndex = getTimeIndex(time - .05);
	selected = true;
	elem = document.getElementById(className + wordIndex);
	scroll(elem);
	selectCurrent(elem);
}

function selectById(id){
	selected = true;
	elem = document.getElementById(className  + id);
	selectCurrent(elem);
}

function keyListener(e){
	if (ie)
		e = window.event
	keyResponseListener(e)
}

var hideKey = 72; // h key
var spaceKey = 32; // space bar
var backArrowKey = 37; 
var forwardArrowKey = 39;
function keyResponseListener(e){
	value = e.keyCode
	if (value==spaceKey){ 
		tog();
		e.cancelBubble = true;
		if (e.stopPropagation) {
			e.stopPropagation();
			e.preventDefault();
		}
		else{
			return false;
		}
	}
	else if (value==backArrowKey){  
		jumpBack();
		e.cancelButton = true
	}
	else if (value==forwardArrowKey){  
		jumpForward();
		e.cancelButton = true
	}	
	else if (value == hideKey){ 
		reading.toggleVisibility("key");
		return;
	}
	else if(value > 48 & value < 58) { // number keys
		goBack(value - 48);
	}
	/*else if(value==80){
		tog()
	}*/
}




/*var currentSlideIndex = -1;
var slideTimeId = -1;
function checkSlide(){
	var time = getTime();
	var previous = 0;
	for (i = 0; i < slideShowTimes.length; i++){
		var slideTime = slideShowTimes[i];
		if (previous <= time & time < slideTime){
			if (currentSlideIndex != i){
				var view = document.getElementById("slide");
				view.innerHTML = "<img src=\"large_images/" + images[i] + "\" >";
				var height = imageHeight[i];
				view.style.visibility =  "visible";
	 			view.style.display = "block";
				if (ie){
					view.style.top = document.body.clientHeight / 2 - height /2 + "px";
				
				}
				else view.style.top = window.innerHeight / 2 - height /2 + "px";
				currentSlideIndex = i;
			}
		}
		previous = slideTime;
	}	
}*/


var min=8;
var max=30;
function increaseFontSize() {
   var p = document.getElementsByTagName('p');
   for(i=0;i<p.length;i++) {

      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
		if(s!=max) {
        	 s += 3;
	      }
      } else {
         var s = 19;
      }


      p[i].style.fontSize = s+"px"
   }
}
function decreaseFontSize() {
	alert("descrease")
   var p = document.getElementsByTagName('p');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
		 if(s!=min) {
        	 s -= 3;
      	}
      } else {
         var s = 13;
      }

      p[i].style.fontSize = s+"px"
   }   
}